package org.sucri.servlet.handler;

import org.sucri.floxs.servlet.User;
import org.sucri.floxs.servlet.RequestHandler;
import org.sucri.floxs.Tools;
import org.apache.commons.collections15.map.MultiKeyMap;
import org.apache.commons.collections15.keyvalue.MultiKey;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.persistence.EntityManagerFactory;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Wen Yu
 * Date: Jul 31, 2007
 * Time: 7:41:18 PM
 * To change this template use File | Settings | File Templates.
 */
abstract public class RequestHandler$ implements RequestHandler
{
  private String mPageName = null;
  private String mAction   = null;

  public RequestHandler$(String page, String action) { mPageName = page; mAction = action; }
  public RequestHandler$(String page, String action, MultiKeyMap<String, RequestHandler> s)
  {
    mPageName = page; mAction = action;
    register(s);
  }

  public String getPageName() { return mPageName; }
  public String getAction()   { return mAction; }

  public boolean register(MultiKeyMap<String, RequestHandler> s)
  {
    if (s == null || (!Tools.good(mAction) && !Tools.good(mPageName))) return false;
    if      (!Tools.good(mPageName)) s.put(new MultiKey<String>("action=" + mAction),   this);
    else if (!Tools.good(mAction))   s.put(new MultiKey<String>("page="   + mPageName), this);
    else                             s.put("age=" + mPageName, "action=" + mAction,     this);

    return true;
  }
  public boolean unregister(MultiKeyMap<String, RequestHandler> s)
  {
    if (s == null || (!Tools.good(mAction) && !Tools.good(mPageName))) return false;
    if      (!Tools.good(mPageName)) s.remove("action=" + mAction);
    else if (!Tools.good(mAction))   s.remove("page="   + mPageName);
    else                             s.remove("page=" + mPageName, "action=" + mAction);

    return true;
  }

  public abstract boolean processRequest(
      EntityManagerFactory emf,
      User                 user,
      HttpServletRequest   req,
      HttpServletResponse  res) throws ServletException, IOException;
}